package com.example.blog.controller;


import com.example.blog.entity.Comment;
import com.example.blog.entity.User;
import com.example.blog.mapper.CommentMapper;
import com.example.blog.service.ICommentService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ly.common.bean.Result;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ly
 * @since 2023-08-03
 */
@RestController
@RequestMapping("/blog/comment")
public class CommentController {

    @Resource
    ICommentService commentService;
    @Resource
    CommentMapper commentMapper;

    @RequestMapping("commit")
    public Result commit(@RequestBody @Valid Comment comment, Errors errors,
                         @SessionAttribute(required = false) User myinfo){
        if(myinfo == null){
           return Result.failure("请先登录系统!", null);
        }
        if(errors.hasErrors()){
           return new Result(-1, "字段验证错误!", errors.getAllErrors());
        }

        comment.setCreateBy(myinfo.getId());

        commentService.save(comment);

        return Result.success("评论发表成功!",null);
    }

    @RequestMapping("queryByAid")
    public Map<String,Object> queryByAid(
            int aid,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "5") int size){
        PageHelper.startPage(page,size,true);
        Page<Comment> p = (Page<Comment>) commentMapper.selectByAid(aid);
        Map<String,Object> ret = new HashMap<>();
        ret.put("total", p.getTotal());
        ret.put("rows", p);
        return ret;
    }

}

